package l.l.w.leetcode.TwoSum;

import java.util.HashMap;

/**
 * Created by llw on 2017/8/22.
 */
public class TwoSum {
    /**
     * 时间复杂度有些大了，有O(n2)
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        int[] result = new int[2];
        for (int i = 0; i < length-1;++i){
            int sub=target-nums[i];
            for (int j = i + 1; j < length; ++j) {
                if(nums[j]==sub){
                    result[0]=i;
                    result[1]=j;
                    return result;
                }
            }
        }
        return null;
    }

    public int[] toSum_ON(int[] nums, int target){
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] result = new int[2];
        for(int i = 0; i < nums.length; ++i){
            if(map.containsKey(target-nums[i])){
                int index1 = map.get(target - nums[i]);
                result[0] = Math.min(index1,i);
                result[1] = Math.max(index1,i);
            }else{
                map.put(nums[i],i);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int [] nums = {2, 7, 11, 15};
        int target = 9;
        int[] result = new TwoSum().twoSum(nums, target);
        System.out.println(result[0]+" " + result[1]);
    }
}
